<?php namespace Phphub\Creators;

use App\Http\Requests\MessageRequest;
use App\Jobs\SendNotifyMail;
use App\Models\Message;
use App\Models\Participant;
use App\Models\Resource;
use App\Models\Thread;
use App\Models\TranslateSubscriber;
use App\Models\UserVipFreeOpeCountLog;
use Phphub\Core\CreatorListener;
use Phphub\Core\Robot;
use App\Models\Topic;
use App\Models\User;
use App\Models\ShareLink;
use App\Models\UserDcoinsLog;
use App\Models\Notification;
use Phphub\Notification\Mention;
use Auth;
use DB;
use Carbon\Carbon;
use Phphub\Markdown\Markdown;
use Illuminate\Support\MessageBag;
use App\Activities\UserPublishedNewTopic;
use App\Activities\BlogHasNewArticle;

class TopicCreator
{
    protected $mentionParser;

    public function __construct(Mention $mentionParser)
    {
        $this->mentionParser = $mentionParser;
    }

    public function create(CreatorListener $observer, $data, $blog = null)
    {
        // 检查是否重复发布
        if ($this->isDuplicate($data)) {
            return $observer->creatorFailed('请不要发布重复内容。');
        }

        $data['user_id'] = Auth::id();
        $data['created_at'] = Carbon::now()->toDateTimeString();
        $data['updated_at'] = Carbon::now()->toDateTimeString();

        // @ user
        $data['body'] = $this->mentionParser->parse($data['body']);

        if ($data['category_id'] == config('phphub.hunt_category_id')) {
            $data['body'] = '分享链接：' . $data['link'] . "\n" . $data['body'];
        }
        $markdown = new Markdown;
        $data['body_original'] = $data['body'];
        $data['body'] = $markdown->convertMarkdownToHtml($data['body']);
        $data['excerpt'] = Topic::makeExcerpt($data['body']);

        $data['source'] = get_platform();

        $data['slug'] = slug_trans($data['title']);
        $topic = new Topic();
        $flag = 0;
        try {
            DB::transaction(function () use (&$topic, &$observer, &$data, &$blog, &$flag) {
                $topic = Topic::create($data);
//                if (! $topic) {
//                    return $observer->creatorFailed($topic->getErrors());
//                }
                // 增加标签
                if (!empty($data['tags'])) {
                    $topic->tag($data['tags']);
                }

                if ($blog) {
                    $blog->topics()->attach($topic->id);
                    // Co-authors
                    if (!$blog->authors()->where('user_id', $topic->user_id)->exists()) {
                        $blog->authors()->attach($topic->user_id);
                    }
                }

                if ($topic->is_draft != 'yes' && $topic->category_id != config('phphub.admin_board_cid')) {
                    app('Phphub\Notification\Notifier')->newTopicNotify(Auth::user(), $this->mentionParser, $topic);
                    app(UserPublishedNewTopic::class)->generate(Auth::user(), $topic);
                }

                if ($topic->isArticle() && $topic->is_draft == 'yes') {
                    Auth::user()->increment('draft_count', 1);
                } elseif ($topic->isArticle()) {
                    Auth::user()->increment('article_count', 1);
                    $blog->increment('article_count', 1);
                    app(BlogHasNewArticle::class)->generate(Auth::user(), $topic, $topic->blogs()->first());
                }
                elseif ($topic->isShareLink())
                {
                    ShareLink::create([
                        'topic_id' => $topic->id,
                        'link' => $data['link'],
                        'site' => domain_from_url($data['link']),
                    ]);

                    //添加私信给管理员,作为翻译原文链接
                    if(isset($data['translation']) && $data['translation'] == 'on')
                    {
                        $recipient = User::findOrFail(1);
                        $subject = Auth::user()->name . ' 给 ' . $recipient->name . ' 的私信。';
                        $thread = Thread::create(['subject' => $subject]);

                        // Message
                        $markdown=new Markdown();
                        $message = $markdown->convertMarkdownToHtml($data['body_original']);
                        Message::create(['thread_id' => $thread->id, 'user_id' => Auth::id(), 'body' => $message]);

                        // Sender
                        $participant = Participant::firstOrCreate(['thread_id' => $thread->id, 'user_id' => Auth::id()]);
                        $participant->last_read = new Carbon;
                        $participant->save();

                        // Recipient
                        $thread->addParticipant($recipient->id);

                        // Notify user by Email
                        $job = (new SendNotifyMail('new_message', Auth::user(), $recipient, null, null, $message))
                            ->delay(config('phphub.notify_delay'));
                        dispatch($job);

                        // notifications count
                        $recipient->message_count++;
                        $recipient->save();
                    }
                }
                elseif($topic->isTranslate())
                {
                    $admin = User::findOrFail(1);
                    $trans_subscriber = TranslateSubscriber::get();
                    Notification::batchNotify('translate_topic_created', $admin, $trans_subscriber, $topic);
                }
                else
                {
                    Auth::user()->increment('topic_count', 1);
                    // 建立资源话题与资源的关联
                    // 12.6 日添加建立源码资源话题与资源的关联
                    if ($data['category_id'] == config('phphub.resources_id')
                        || $data['parent_category_id'] == config('phphub.resources_id')
                    ) {
                        $resource = Resource::query()->find($data['resource_id']);
                        if (!$resource) {
                            $topic->delete();
                            $flag = -1;
                            return; //$observer->creatorFailed('资源不存在!');
                        }
                        $resource->topic_id = $topic->id;

                        $resource->cost = $data['resource_point'];
                        $resource->cost_type = 1;//积分
                        $resource->type = $data['resource_type'] ?? 0;
                        $resource->category = $data['resource_category'] ?? 0;
                        $resource->save();
                    } else if ($data['category_id'] == config('phphub.algorithm_sources_id')
                        || $data['parent_category_id'] == config('phphub.algorithm_sources_id')
                    ) {
                        $resource = Resource::query()->find($data['resource_id']);
                        if (!$resource) {
                            $topic->delete();
                            $flag = -1;
                            return; //$observer->creatorFailed('资源不存在!');
                        }
                        $resource->topic_id = $topic->id;
                        $resource->cost = $data['resource_dcoin'];
                        $resource->cost_type = 2;//D币
                        $resource->algorithm_lang = $data['algorithm_lang'] ?? 0;
                        $resource->type = $data['resource_type'] ?? 0;
                        $resource->category = $data['resource_category'] ?? 0;
                        $resource->save();
                    } //作业帮扣除D币数
                    elseif ($data['category_id'] == config('phphub.homework_help_id')
                        || $data['parent_category_id'] == config('phphub.homework_help_id')) {
                        $vipFreeCountLog = UserVipFreeOpeCountLog::getLatestLog(Auth::user()->id);
                        if (!empty($vipFreeCountLog) && $vipFreeCountLog->free_home_help_remain_count > 0) {

                            $newVipFreeCountLog = new UserVipFreeOpeCountLog();
                            $newVipFreeCountLog->user_id = Auth::user()->id;
                            $newVipFreeCountLog->ope = UserVipFreeOpeCountLog::EXPEND_OPE;
                            $newVipFreeCountLog->free_home_help_ope_count = 1;
                            $newVipFreeCountLog->free_home_help_remain_count = --$vipFreeCountLog->free_home_help_remain_count;
                            $newVipFreeCountLog->free_resource_ope_count = 0;
                            $newVipFreeCountLog->free_resource_remain_count = $vipFreeCountLog->free_resource_remain_count;
                            $newVipFreeCountLog->free_algorithm_sources_ope_count = 0;
                            $newVipFreeCountLog->free_algorithm_sources_remain_count = $vipFreeCountLog->free_algorithm_sources_remain_count;
                            $newVipFreeCountLog->remark = '作业帮提问';
                            $newVipFreeCountLog->save();
                        } else {
                            $dcoin_statistic = UserDcoinsLog::dcoinStatistic(Auth::id());
                            $dcoin_transfer = UserDcoinsLog::HOMEWORK_MINUS_DCOINS;
                            //若是vip则打折
                            $userVipInfo = Auth::user()->vipInfo()->first();
                            if (!empty($userVipInfo)) {
                                $dcoin_transfer = UserDcoinsLog::HOMEWORK_MINUS_DCOINS * $userVipInfo->homework_help_discount;
                            }
                            $userDcoinsLog = new UserDcoinsLog();
                            $userDcoinsLog->user_id = Auth::id();
                            $userDcoinsLog->type = 2;//消耗
                            $userDcoinsLog->dcoins = -$dcoin_transfer;
                            $userDcoinsLog->remain_dcoins = $dcoin_statistic['remain_dcoins'] - $dcoin_transfer;
                            $userDcoinsLog->reason_type = UserDcoinsLog::REASON_TYPE_HOMEWORK_MINUS;//D币积分转换
                            $userDcoinsLog->remark = '作业帮消耗';
                            $userDcoinsLog->save();
                        }
                        //消耗D币,通知用户
                        $admin = User::findOrFail(1);
                        Notification::notify('homework_minus_dcoins', $admin, $topic->user, $topic);
                    }
                }


                $topic->collectImages();


            });

            if ($flag == -1) {
                return $observer->creatorFailed('资源不存在!');
            }
            return $observer->creatorSucceed($topic);
        } catch (\Illuminate\Database\QueryException $ex) {
            return $observer->creatorFailed($topic->getErrors());
        }

    }

    public function isDuplicate($data)
    {
        $last_topic = Topic::where('user_id', Auth::id())
            ->orderBy('id', 'desc')
            ->first();
        return $last_topic !== null && !empty($last_topic) && strcmp($last_topic->title, $data['title']) === 0;
    }
}
